<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou\timeframe;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\mysql\KsTimeFrameTaskModel;
use app\service\batch\kuaishou\UnitTimeFrameService;
use app\service\batch\KuaiShouBatchService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class UnitTimeFrameTaskPushWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ks_unit_time_frame_task_push_work');
        $this->setDescription('快手批量组投放时段修改任务拉取');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('快手批量组投放时段修改任务拉取开始');
        $st = time() + 300;
        $key = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['unit_frame_time'];
        $redis = Cache::store('redis')->handler();
        while (time() < $st) {
            try {
                $frameTaskId = intval($redis->lPop($key));
                if (! $frameTaskId) {
                    usleep(500000);
                    continue;
                }
                $timeFrameTaskModel = (new KsTimeFrameTaskModel())->findOrEmpty($frameTaskId);
                if (! $timeFrameTaskModel->getKey()) {
                    return self::setError('未知的投放时段id');
                }
                $this->getOutputMessage('快手批量组投放时段修改任务拉取[' . $frameTaskId . ']开始');
                // 处理中
                UnitTimeFrameService::setStatus($timeFrameTaskModel, KsTimeFrameTaskModel::STATUS_BEING);
                if (! KuaiShouBatchService::batchUintFrameTime($timeFrameTaskModel)) {
                    // 待执行
                    UnitTimeFrameService::setStatus($timeFrameTaskModel, KsTimeFrameTaskModel::STATUS_WAIT);
                    $this->getOutputMessage('快手批量组投放时段修改任务拉取[' . $frameTaskId . ']失败,' . KuaiShouBatchService::getError(0));
                } else {
                    $this->getOutputMessage('快手批量组投放时段修改任务拉取[' . $frameTaskId . ']成功');
                }
            } catch (\Exception $e) {
                $this->getOutputMessage('快手批量组投放时段修改任务拉取失败,' . $e->getMessage());
            }
        }
        $this->getOutputMessage('快手批量组投放时段修改任务拉取结束');
    }
}
